package com.imooc.api.intercept;

import com.imooc.base.BaseInfoProperties;
import com.imooc.exceptions.GraceException;
import com.imooc.exceptions.GraceExceptionHandler;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.grace.utils.IPUtil;
import com.imooc.grace.utils.RedisOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class SMSInterceptor extends BaseInfoProperties implements HandlerInterceptor {

    @Autowired
    public RedisOperator redis;


    //进入接口之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //60s 限制 获得用户ip
        String userIp = IPUtil.getRequestIp(request);
        Boolean isExist = redis.keyIsExist(MOBILE_SMSCODE + ":" +userIp);
        if(isExist){
            log.error("短息您发送频率过高");
            GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
            return false;
        }
        return true;
    }
    //进入接口之后渲染之前
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    //所有过程之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
